package com.example.school.service;

import com.example.school.entity.Student;
import com.example.school.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;



    public boolean login(String username, String password) {
        Student Student = studentMapper.getByUsername(username);
        if (Student != null && Student.getPassword().equals(password)) {
            return true;
        }
        return false;
    }


    @Transactional
    public boolean changePassword(String username, String oldPassword, String newPassword) {
        // 根据用户名查找学生
        Student student = studentMapper.findByUsername(username);

        // 如果学生不存在或旧密码不匹配，则返回false
        if (student == null || !student.getPassword().equals(oldPassword)) {
            return false;
        }

        // 更新密码
        int rowsAffected = studentMapper.updatePassword(username, newPassword);

        return rowsAffected > 0;
    }


    public Map<String, Object> searchStudents(Map<String, Object> params) {
        List<Student> students = studentMapper.getStudent(params);
        Map<String, Object> retData = new HashMap<>();
        if (students != null && !students.isEmpty()) {
            retData.put("code", 200);
            retData.put("message", "查询成功");
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (Student student : students) {
                Map<String, Object> studentInfo = new HashMap<>();
                studentInfo.put("username", student.getUsername());
                studentInfo.put("name", student.getName());
                studentInfo.put("classId", student.getClassId());
                studentInfo.put("studentId", student.getStudentId());
                resultList.add(studentInfo);
            }
            retData.put("data", resultList);
        } else {
            retData.put("code", 500);
            retData.put("message", "未找到符合条件的学生");
        }
        return retData;
    }

    public Student getIdByUsername(String username){
        return studentMapper.getIdByUsername(username);
    }


}
